package com.example.demo.controller;

import cn.hutool.core.bean.BeanUtil;
import com.example.demo.model.*;
import com.example.demo.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2024-05-04
 * Time: 10:11
 */
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private IUserService userService;

    @PostMapping("")
    @ApiOperation("新增用户")
    public void saveUser(@RequestBody UserFormDTO userFormDTO) {
        // 类型转换
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        // 新增
        userService.save(user);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    public void removeUserById(@PathVariable("id") Long userId) {
        userService.removeById(userId);

    }

    @GetMapping("/{id}")
    @ApiOperation("根据 id 查询用户")
    public UserVO queryUserById(@PathVariable("id") Long userId) {
        // 查询
        User user = userService.getById(userId);
        // 类型转换并返回
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        return userVO;
    }

    @GetMapping("")
    @ApiOperation("根据 Id 集合查询用户以及用户地址列表")
    public List<UserVO> queryUserByIds(@RequestParam("ids") List<Long> ids) {
        return userService.queryUserAndAddressesByIds(ids);
    }

    @PutMapping("{id}/deduction/{money}")
    @ApiOperation("根据 id 扣减用户余额")
    public void deductBalance(@PathVariable("id") Long id,@PathVariable("money") Integer money) {
        if (id == null || money == null || money <= 0) {
            return;
        }
        userService.deductBalanceById(id,money);
    }

    @GetMapping("/list")
    @ApiOperation("复杂条件查询用户")
    public List<UserVO> queryUser(UserQuery userQuery) {
        // 查询
        List<User> users = userService.queryUsers(userQuery.getName(),userQuery.getStatus(),userQuery.getMinBalance(),userQuery.getMaxBalance());
        // 类型转换并返回
        return BeanUtil.copyToList(users,UserVO.class);
    }

    @GetMapping("/page")
    @ApiOperation("复杂条件分页查询用户")
    public PageResult<UserVO> pageQueryUser(UserQuery userQuery) {
        return userService.pageQueryUser(userQuery);
    }
}
